package cn.itzzx.lagou.minicat.request;

import cn.itzzx.lagou.minicat.mapper.Mapper;
import cn.itzzx.lagou.minicat.response.Response;
import cn.itzzx.lagou.minicat.servlet.HttpServlet;
import cn.itzzx.lagou.minicat.utils.HttpProtocolUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.util.List;
import java.util.Map;

/**
 * TODO
 *
 * @author Martin
 * @since 1.0
 */
public class RequestProcessor extends Thread {

    private Socket socket;

    private Mapper mapper;

    public RequestProcessor(Socket accept, Mapper mapper) {
        this.socket = accept;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            //从输入流中获取请求信息
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            // /demo1/lagou
            String url = request.getUrl();

            String[] split = url.split("/");
            //demo1
            String appName = split[1];
            String uri = url.substring(appName.length() + 1);
            if (!existsApp(appName)) {
                response.output(HttpProtocolUtil.getHttpHeader404());
                return;
            }
            //根据当前求求的uri获取Servlet
            List<Mapper.MappedHost> hosts = mapper.hosts;
            String webappPath = "";
            HttpServlet httpServlet = null;
            for (Mapper.MappedHost host : hosts) {
                //获取默认Host <Host name="localhost" appBase="/Users/webapps">
                if (mapper.getDefaultHostName().equals(host.getName())) {
                    webappPath = host.getAppBase() + "/" + appName;
                    Mapper.MappedContext mappedContext = host.getContextMap().get(appName);
                    httpServlet = mappedContext.getWrapper().get(uri);
                }
            }
            if (httpServlet == null) {
                //静态资源处理
                response.outputHtml(webappPath + uri);
            } else {
                //动态资源servlet请求
                httpServlet.service(request, response);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    private boolean existsApp(String appName) {
        boolean flag = false;
        for (Mapper.MappedHost host : mapper.hosts) {
            Mapper.MappedContext mappedContext = host.getContextMap().get(appName);
            if (mappedContext != null) {
                flag = true;
            }
        }
        return flag;
    }
}
